package work.lianbiao;


import work.ListNode;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Problem2 {


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode top1 = l1;
        ListNode top2 = l2;
        ListNode wdh = new ListNode(1);
        ListNode pre = wdh;
        while (l1.next != null && l2.next != null) {
            l1 = l1.next;
            l2 = l2.next;
        }
        if (l1.next == null) {
            while (l2.next != null) {
                ListNode node = new ListNode(0);
                l1.next = node;
                l1 = l1.next;
                l2 = l2.next;
            }
        } else {
            while (l1.next != null) {
                ListNode node = new ListNode(0);
                l2.next = node;
                l2 = l2.next;
                l1 = l1.next;
            }
        }
        l1 = top1;
        l2 = top2;
        int b = 0;
        while (l1 != null && l2 != null) {
            int sum = l1.val + l2.val + b;
            int a = sum % 10; //个位数
            b = sum / 10; //十位数
            ListNode node = new ListNode(a);
            pre.next = node;
            pre = pre.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        if (b == 1) {
            ListNode node = new ListNode(b);
            pre.next = node;
        }
        ListNode.printList(wdh.next);
        return wdh.next;
    }


    public static void main(String[] args) {
        int[] a = {2, 4, 3, 1};
        int[] b = {5, 6, 4};
        ListNode node = ListNode.listNodeFromArray(a);
        ListNode node1 = ListNode.listNodeFromArray(b);
        Problem2 problem2 = new Problem2();
        ListNode node2 = problem2.addTwoNumbers1(node1, node);
        node2.printList();

    }


    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {

        ListNode list1 = l1;
        ListNode list2 = l2;
        ListNode ans = new ListNode(0);
        ListNode ans1 = ans;
        int a = 0;
        while (list1 != null && list2 != null) {
            int b = (list1.val + list2.val + a) % 10;
            ListNode listNode = new ListNode(b);
            a = (list1.val + list2.val + a) / 10;
            ans.next = listNode;
            ans = ans.next;
            list1 = list1.next;
            list2 = list2.next;
        }
        while (list2 != null) {
            int b = (list2.val + a) % 10;
            ListNode listNode = new ListNode(b);
            a = (list2.val + a) / 10;
            ans.next = listNode;
            ans = ans.next;
            list2 = list2.next;
        }
        while (list1 != null) {
            int b = (list1.val + a) % 10;
            ListNode listNode = new ListNode(b);
            a = (list1.val + a) / 10;
            ans.next = listNode;
            ans = ans.next;
            list1 = list1.next;
        }
        if (a == 1) {
            ans.next = new ListNode(1);
        }
        return ans1.next;
    }



}
